package com.zjh.config;


import com.zjh.pojo.*;
import com.zjh.service.MenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * @Auther: zjh
 * @Date: 2025/9/28 - 09 - 28 - 21:46
 * @Description: com.zjh.config
 * @version: 1.0
 */
@Configuration
@RequiredArgsConstructor
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    private final MenuService meauService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        for (Meau meau : meauService.getAllMenu()) {
            if (antPathMatcher.match(meau.getPattern(), requestUrl)) {
                ArrayList<ConfigAttribute> configAttributes = new ArrayList<>();
                for(Role role : meau.getRoles()) {
                    configAttributes.add(new SecurityConfig(role.getName()));
                }
                return configAttributes;
            }
        }
        return Collections.emptyList();
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return Collections.emptyList();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
